package org.cloud.framework.controller;

import net.sf.json.JSONObject;
import org.cloud.framework.ueditor.ActionEnter;
import org.cloud.framework.utils.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.TransformerHandler;
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 恢复工具
 */
@RestController
public class UnpackContoller extends BaseContoroller{

    @Value("${data.file.backup}")
    private String unpackPath;
    @Value("${data.file.prefix}")
    private String prefix;
    @Value("${data.file.rootpath}")
    private String rootpath;
    @Value("${jdbc.driver-class-name}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    IdWorker idWorker = new IdWorker(2);
    private static StringBuffer sb = new StringBuffer();
    private static String status = "0";
    //附件上传
    @RequestMapping(value="/backupUpload",method = RequestMethod.POST)
    @ResponseBody
    public void backupUpload(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam("file") MultipartFile file) throws Exception {
        HashMap<String, Object> dMap = new HashMap<String, Object>();
        String path ="";
        String fileName = "";
        boolean flag = false;
        if (file.getSize() > 0) {
            fileName = file.getOriginalFilename();

            path = unpackPath;
            File f = new File(path);
            if(!f.exists()){
                f.mkdirs();
            }
            byte[] bytes = file.getBytes();
            BufferedOutputStream buffStream =
                    new BufferedOutputStream(new FileOutputStream(new File(path + "/" + fileName)));
            buffStream.write(bytes);
            buffStream.close();
            System.out.println("【文件上传地址】"+path + "/" + fileName);
            flag = true;
        }
        if (flag == true) {
            if(unpackPath.endsWith("/") || unpackPath.endsWith("\\")){
                dMap.put("info", unpackPath + fileName);
            }else{
                dMap.put("info", path + "/" +fileName);
            }
        } else {
            dMap.put("info", "error");
        }
        String result = formatToJson(dMap);
        super.pringWriterToPage(result, "application/json", response);
    }

    //一键解包
    @RequestMapping("aKeyToUnpack")
    @ResponseBody
    public void aKeyToUnpack(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HashMap<String, Object> dMap = new HashMap<String, Object>();
        String path = request.getParameter("path");
        status = "0";
        sb = new StringBuffer();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //数据库连接

                Connection conn = null;
                try {
                    conn = JdbcUtils.getConnection(driver, url, username, password);

                    sb.append("开始...");

                    String fileName = new File(path).getName();
                    String dirName= fileName.substring(0,fileName.indexOf(".zip"));
                    System.out.println("正在解压...");

                    sb.append(",正在解压...");

                    FileTool.unzip(path ,unpackPath+"/",false);
                    System.out.println("解压完成！正在恢复数据...");

                    sb.append(",解压完成！正在恢复数据...");

                    File file = new File(unpackPath+"/"+dirName);
                    File[] files = file.listFiles();

                    //读取xml
                    SAXParserFactory factory = SAXParserFactory.newInstance();
                    SAXParser parser = factory.newSAXParser();
                    List<Map<String, Object>> listMap = null;
                    List<String> sqls = new ArrayList<>();

                    //插入数据库
                    StringBuffer sql = new StringBuffer();
                    StringBuffer value = new StringBuffer();
                    for (int i = 0; i < files.length; i++) {
                        sqls = new ArrayList<>();
                        listMap = new ArrayList<>();
                        if(files[i].getName().endsWith(".xml")){
                            System.out.println("正在读取:"+files[i].getName());

                            sb.append(",正在读取:"+files[i].getName());

                            String name = files[i].getName().substring(0,files[i].getName().indexOf(".xml"));
                            ReadXml readXml = new ReadXml("//entities/entity",0,100000,false);
                            parser.parse(files[i].getAbsolutePath(), readXml);
                            listMap = readXml.list;
                            readXml.list = null;

                            System.out.println("读取完成！正在写入数据库....");

                            sb.append(",读取完成！正在写入数据库....");

                            String classid = "";
                            ResultSet resultSet1 = JdbcUtils.executeSql(conn, "SELECT id FROM classes WHERE name_en='" + name + "'");
                            List<Map<String, Object>> result1 = JdbcUtils.getResult(resultSet1);
                            if(result1.size()>0){
                                classid = result1.get(0).get("id").toString();
                            }

                            for (int j = 0; j < listMap.size(); j++) {
                                sql = new StringBuffer();
                                value = new StringBuffer();
                                sql.append("INSERT INTO ").append(prefix).append(name).append("(");
                                value.append(" VALUES(");
                                for (String key:listMap.get(j).keySet()) {
                                    sql.append(key).append(",");
                                    value.append("'").append(listMap.get(j).get(key)).append("',");
                                }
                                sql.append("create_user_id,create_org_id,version,status,data_source,classes_id)");
                                value.append("'1','48','1.0','0','init','").append(classid).append("');");

                                sqls.add(sql.toString()+value.toString());

                                ResultSet resultSet = JdbcUtils.executeSql(conn, "SELECT id FROM " + prefix + name + " WHERE id='" + listMap.get(j).get("id") + "'");
                                List<Map<String, Object>> result = JdbcUtils.getResult(resultSet);
                                JdbcUtils.close(resultSet);
                                if(result.size()>0){//数据库中已经存在
                                    JdbcUtils.delete(conn,"DELETE FROM " + prefix + name + " WHERE id='" + listMap.get(j).get("id") + "'");
                                }
                                System.out.println(sql.toString() + value.toString());
                                JdbcUtils.insert(conn, sql.toString() + value.toString());
                                //JdbcUtils.close(rs);

                            }
                            listMap = null;
                            //JdbcUtils.batchInsert(conn,sqls);
                            System.out.println("写入完成："+files[i].getName());

                            sb.append(",写入完成："+files[i].getName());
                        }
                    }

                    System.out.println("恢复数据完成！正在转移文件...");
                    sb.append(",恢复数据完成！正在转移文件...");
                    FileTool.copyFolder(unpackPath+"/"+dirName+"/file",rootpath+"/file");

                    System.out.println("转移文件完成！正在转移图片...");
                    sb.append(",转移文件完成！正在转移图片...");

                    FileTool.copyFolder(unpackPath+"/"+dirName+"/image",rootpath+"/image");
                    System.out.println("转移图片完成！一键解包完成！");

                    sb.append(",转移图片完成！一键解包完成！");

                }catch (Exception e){
                    e.printStackTrace();
                    System.out.println("解包错误！");
                    sb.append(",解包错误！");
                }finally {
                    if(conn!=null){
                       JdbcUtils.close(conn);
                    }
                }
                status = "1";
            }
        }).start();
        dMap.put("result","success");
        dMap.put("msg","启动成功");
        String s = super.formatToJson(dMap);
        super.pringWriterToPage(s, "application/json", response);
    }
    //一键解包
    @RequestMapping("unpackBar")
    @ResponseBody
    public void unpackBar(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HashMap<String, Object> dMap = new HashMap<String, Object>();

        dMap.put("result","success");
        dMap.put("msg",sb.toString());
        dMap.put("status",status);
        String s = super.formatToJson(dMap);
        System.out.println(s);
        super.pringWriterToPage(s, "application/json", response);
    }

}
